use axum::{
    Json,
    response::{Response, IntoResponse},
    http::StatusCode,
};
use serde::Serialize;

// 统一响应结构
#[derive(Debug, Serialize)]
pub struct ApiResponse<T: Serialize> {
    pub code: u16,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<T>,
}

impl<T: Serialize> ApiResponse<T> {
    pub fn new(code: u16, message: &str, data: Option<T>) -> Self {
        Self {
            code,
            message: message.to_string(),
            data,
        }
    }

    pub fn success(data: T) -> Self {
        Self::new(200, "success", Some(data))
    }

    pub fn error(message: &str) -> Self {
        Self::new(500, message, None)
    }
}

// 实现 IntoResponse 以便直接返回
impl<T: Serialize> IntoResponse for ApiResponse<T> {
    fn into_response(self) -> Response {
        let status = StatusCode::from_u16(self.code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
        (status, Json(self)).into_response()
    }
}